import os
import json,hashlib
import tornado.ioloop
import tornado.web,yaml,time
md_info_path=os.path.dirname(os.path.abspath(__file__))+os.sep+'md_info'
def read_yaml(path):
    #读取用户目录下的yaml配置文件
    with open(path, 'r',encoding='utf-8') as file:  
       return yaml.safe_load(file)
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        with open(os.path.dirname(os.path.abspath(__file__))+os.sep+'templates'+os.sep+'index.html','r',encoding='utf-8')as f:
            self.write(f.read())

class MarkdownFileHandler(tornado.web.RequestHandler):
    def get(self):
        dir_id = self.get_argument("dir_id")
        file_id = self.get_argument("file_id")
        dir_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'md_info')
        md_path=os.path.join(dir_path,dir_id,'md_files',file_id,'main.md')
        LhpDocs_img=f'![Alt Text](/LhpDocs_img/{dir_id}/md_files/{file_id}/'#修改静态文件地址
        if os.path.isfile(md_path):
            with open(md_path, "r", encoding="utf-8") as f:
                content = f.read()
            self.set_header("Content-Type", "text/plain; charset=utf-8")
            self.write(content.replace("![Alt Text](",LhpDocs_img))
        else:
            self.set_status(404)
            self.write("File not found")

class MarkdownInfoHandler(tornado.web.RequestHandler):
    def get(self):
        # 假设你想返回一个关于 Markdown 文件的信息的 JSON 对象
        # 这里我们简单地创建一个示例数据
        info = {
        }
        dir_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'md_info')
        dir_lst=os.listdir(dir_path)
        for dir_id in dir_lst:
            #获取目录基础信息
            try:
                dir_data=read_yaml(os.path.join(dir_path,dir_id,'main.yaml'))
            except:
                continue
            try:
                info[dir_id]=dir_data
                info[dir_id]['dict']={}
            except:
                del info[dir_id]
                continue
            #获取内容信息
            md_files_path=os.path.join(dir_path,dir_id,'md_files')
            try:
                md_files=os.listdir(md_files_path)
            except:
                continue
            for file_id in md_files:
                info[dir_id]['dict'][file_id]=read_yaml(os.path.join(md_files_path,file_id,'main.yaml'))
        self.set_header("Content-Type", "application/json")
        self.write(json.dumps(info, indent=4, ensure_ascii=False))

class read_img(tornado.web.RequestHandler):
    def get(self,path_parts):
        # 找到LhpDocs_img之后的部分
        # 注意：这里假设URL中确实包含/LhpDocs_img/，并且我们想要获取其后的所有部分
        try:
            file_path=os.path.join(md_info_path,path_parts)
            if not file_path :
                self.set_status(400)
                self.write({"error": "Invalid file path"})
                self.finish()
                return
            # 计算文件的ETag（用于缓存验证）
            file_etag = hashlib.md5(file_path.encode('utf-8')).hexdigest()
            # 检查If-None-Match头以确定是否使用缓存
            if_none_match = self.request.headers.get('If-None-Match', None)
            if if_none_match == file_etag:
                self.set_status(304)  # Not Modified
                self.finish()
                return
            
            # 设置响应头
            self.set_header('ETag', file_etag)
            self.set_header('Content-Type', 'image/png')
            self.set_header('Cache-Control', 'public, max-age=31536000')  # 1年缓存
            self.set_header('Expires', time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time() + 31536000)))
            # 读取并发送PNG文件内容
            with open(file_path, 'rb') as f:
                self.write(f.read())
            self.finish()
        except:
            self.set_status(400)
            self.write({"error": "Invalid file type"})
            self.finish()

def params():
    return [
        (r"/", MainHandler),
        (r"/md_file", MarkdownFileHandler),
        (r"/md_info", MarkdownInfoHandler),
        (r"/%s/(.*)"%'LhpDocs_img',read_img),
        (r"/%s/(.*)"%'LhpDocs_static', tornado.web.StaticFileHandler, {"path": os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")}),
    ]
def make_app():
    return tornado.web.Application(params(), 
      debug=True)

if __name__ == "__main__":
    app = make_app()
    app.listen(10011)
    print("Server is running on http://localhost:10011")
    tornado.ioloop.IOLoop.current().start()